import React, { Component } from 'react';
import ReactDom from 'react-dom';
import util from "@/common/util";
import layer from "@/common/layer";
import cakeflakes from "@/common/cakeflakes";
import axios from 'axios';
import ReactSwiper from 'reactjs-swiper';
import jquery from 'jquery';


class Crabprogress extends Component {
    constructor(props) {
        super(props);
        this.state = {
            guyslist: [],
            prodetail: {},
            bgcolor: false,
            listlength: 0,
            assistCount: 0,
            name: '',
            tellphone: '',
            address: '',
            second: 0,
            code: ''
        }
        this.valids = [
            {
                key: 'name',
                func(str) {
                    if (str.length === 0) {
                        jquery(".errormsg").html("姓名不能为空")
                        return false
                    } else {
                        jquery(".errormsg").empty()
                    }
                    return true
                }
            },
            {
                key: 'tellphone',
                func(str) {
                    if (str.length !== 11) {
                        jquery(".errormsg").html("手机号码格式错误")
                        return false
                    } else {
                        jquery(".errormsg").empty()
                    }
                    return true
                }
            },
            {
                key: 'code',
                func(str) {
                    if (str.length === 0) {
                        jquery(".errormsg").html("验证码不能为空")
                        return false
                    } else {
                        jquery(".errormsg").empty()
                    }
                    return true
                }
            },
            {
                key: 'address',
                func(str) {
                    if (str.length === 0) {
                        jquery(".errormsg").html("家庭地址不能为空")
                        return false
                    }
                    return true
                }
            }
        ]
    }

    componentDidMount() {
        this.getprogress()
        this.prodetail()
        jquery('.noprizeclose').click(function () {
            jquery(".dialogno").css("display", 'none')
        })
        var that = this
        jquery('.getcrabbtn').click(function () {
            if (that.state.listlength >= that.state.assistCount) {
                that.isclick()
            } else {
                if (that.state.overplus <= 0) {
                    layer.open({
                        content: "您来晚了，奖品发完了哦",
                        btn: "好的"
                    })
                } else {
                    layer.open({
                        content: "您还未助力完成哦",
                        btn: "好的"
                    })
                }
            }
        })
    }

    async isprize() {
        var proid = util.getQuery().id;
        var openid = sessionStorage.getItem('openid')
        let res = await util.rjax({
            url: '/prizeUser/receivePrize?prizeId=' + proid + '&openId=' + openid + "&type=1",
            type: 'post'
        }).catch((e) => {
            if (e.data.code === 10011051) {
                jquery('.dialogno').show()
            }
        })
        if (res) {
            jquery('.dialogbox').show()
        }
    }

    async isclick() {
        var proid = util.getQuery().id;
        var openid = sessionStorage.getItem('openid')
        let res = await util.rjax({
            url: '/prizeUser/isReceive/' + proid + '?openId=' + openid,
            type: 'get'
        }).catch((e) => {//没有领过
            if (e.data.code === 10011052) {
                this.isprize()
            }
        })
        console.log("isclick:  " + res)
        if (res) {//领过，且data为1时表示中奖了
            if (res.data === 1) {
                var index = layer.open({
                    content: "您已经领过该奖品了",
                    btn: "好的",
                    yes: function () {
                        layer.close(index);
                        jquery('.dialogbox').show()
                    }
                })
            }
        }
    }

    async getprogress() {
        var proid = util.getQuery().id;
        var openid = sessionStorage.getItem('openid')
        let res = await util.rjax({
            url: '/assistFriend/assistProgress?prizeId=' + proid + '&openId=' + openid,
            type: 'get'
        }).catch((res) => {
            console.log(res)
        })
        if (res) {
            this.setState({ guyslist: res.data })
            this.setState({ listlength: this.state.guyslist.length })
        }
    }

    async prodetail() {
        var proid = util.getQuery().id;
        let res = await util.rjax({
            url: '/prize/getPrize/?prizeId=' + proid + '&type=1',
            type: 'get',
        })
        this.setState({ prodetail: res.data });
        this.setState({ assistCount: this.state.prodetail.assistCount })
        this.setState({ overplus: this.state.prodetail.total - this.state.prodetail.count })
    }

    async beforeSendCode() {
        if (this.state.second !== 0) { return }
        if (this.state.tellphone.length < 11) {
            jquery(".errormsg").html("手机格式错误")
            return
        } else {
            jquery(".errormsg").empty()
        }
        this.setState({
            second: 60
        });

        let time = setInterval(() => {
            if (this.state.second < 1) {
                clearInterval(time)
            } else {
                this.setState({
                    second: this.state.second - 1
                })
            }
        }, 1000)

        let phone = this.state.tellphone
        let res = await axios.get(`${util.host}/auth/code/sms`, {
            params: {
                deviceId: phone,
                phone: phone
            }
        })

        if (res.data.success) {
            jquery(".errormsg").html("验证码发送成功")
        } else {
            jquery(".errormsg").html("手机号码格式错误")
        }
    }

    async beforeSubmit() {
        for (let item of this.valids) {
            if (!item.func(this.state[item.key])) {
                return;
            }
        }

        var openId = sessionStorage.getItem("openid")
        let sendobj = {
            address: this.state.address,
            name: this.state.name,
            openId: openId,
            phone: this.state.tellphone,
            smsCode: this.state.code,
            type: 1  //1表示助力活动
        }

        let res = await util.rjax({
            url: '/prizeUser/insertPrizeUser',
            type: "POST",
            data: sendobj
        }).catch((e) => {
            layer.open({
                content: e.data.msg,
                btn: "好的"
            })
        })
        if (res) {
            layer.open({
                content: "提交成功！",
                btn: '好的'
            })
            this.setState({ name: '' })
            this.setState({ address: '' })
            this.setState({ tellphone: '' })
            this.setState({ second: 0 })
            this.setState({ code: '' })
        }
    }


    nameChange(e) {
        this.setState({
            name: e.target.value
        })
    }

    phoneChange(e) {
        this.setState({
            tellphone: e.target.value
        })
    }

    codeChange(e) {
        this.setState({
            code: e.target.value
        })
    }

    addressChange(e) {
        this.setState({
            address: e.target.value
        })
    }

    async closedialog() {
        jquery('.dialogbox').hide()
    }

    render() {
        let guyslist = this.state.guyslist.map((item, index) => {
            return (
                <li key={index}>
                    <span className="recordnum">{index + 1}.</span>
                    <img src={item.image} alt="" />
                    <span className="guyname">{item.name}</span>
                    <span className="zai"><i></i>帮您助力了</span>
                </li>
            )
        })
        return (
            <div>
                <div id="crab">
                    <div className="crabcard">
                        <div className="left">
                            <img className="crabpic" src={this.state.prodetail.image} alt="" />
                            <p className="crabintr">{this.state.prodetail.introduction}</p>
                        </div>
                        <div className="right">
                            <div className="num">
                                <p>数量：<i>{this.state.prodetail.total}份</i></p>
                                <p>剩余：<i>{this.state.prodetail.total - this.state.prodetail.count}份</i></p>
                            </div>
                            <button className="getcrabbtn">抢</button>
                        </div>
                    </div>
                    <div className="progress">
                        <h4>—— 我的助力 ——</h4>
                        <ul>
                            {guyslist}
                        </ul>
                    </div>
                </div>
                <div className="dialogbox">
                    <div className="dialog">
                        <img className="closebtn" onClick={this.closedialog.bind(this)} src="http://img0.rongsue.com/FqRJoUj9TKA1FKqZUSdG51Kumhed" alt="" />
                        <p className="gongxi">恭喜您！</p>
                        <p className="award">获得<i>{this.state.prodetail.introduction}</i>一份</p>
                        <div style={{ position: 'relative' }}>
                            <img className="crabpic" src={this.state.prodetail.image} alt="" />
                        </div>
                        <div className="applyinput">
                            <div style={{ position: "relative" }}>
                                <span className="phonehead">姓名</span>
                                <input type="text" className="text" autoComplete="off" placeholder="姓名" value={this.state.name} onChange={this.nameChange.bind(this)} maxLength="11" />
                            </div>

                            <div style={{ position: "relative" }}>
                                <span className="phonehead">+86</span>
                                <input type="text" className="text" autoComplete="off" placeholder="请输入手机号" value={this.state.tellphone} onChange={this.phoneChange.bind(this)} maxLength="11" />
                            </div>

                            <div style={{ position: "relative" }}>
                                <span className="codehead">验证码</span>
                                <input type="text" className="text" autoComplete="off" placeholder="请输入验证码" value={this.state.code} onChange={this.codeChange.bind(this)} />
                                <input type="button" className="yzbtn" value={(this.state.second === 0) ? '验证码' : `剩余${this.state.second}秒`} onClick={this.beforeSendCode.bind(this)} />
                            </div>

                            <div style={{ position: "relative" }}>
                                <span className="cityhead">家庭地址</span>
                                <input type="text" className="text" autoComplete="off" placeholder="江苏省南京市" value={this.state.address} onChange={this.addressChange.bind(this)} />
                            </div>

                            <span className="errormsg"></span>
                            <input type="button" className="btn" value="确定" onClick={this.beforeSubmit.bind(this)} />
                        </div>
                        <p className="tishi">完善个人信息领奖，关注微信公众号<b>【苏e栈】</b>输入 <i>“领奖”</i>获知奖品发放时间。</p>
                        <p className="question">若有疑问，可私信苏e栈公众号，</p>
                        <p className="question">客服尽快与您取得联系。</p>
                        <img className="qrcodeimg" src="/assets/wechat/code.png" alt="" />
                        <p className="attrqrcode">长按识别二维码关注</p>
                    </div>
                </div>
                <div className="dialogno">
                    <div>
                        <p>很抱歉，手速太慢！</p>
                        <p>请试试其他助力商品吧!</p>
                        <button className="noprizeclose">好吧</button>
                    </div>
                </div>
            </div>
        )
    }
}
ReactDom.render(<Crabprogress />, document.getElementById("app"));